package chapter2.eg5;

import io.netty.util.CharsetUtil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Date;

public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {

  private AsynchronousSocketChannel channel;

  public ReadCompletionHandler(AsynchronousSocketChannel channel) {
    this.channel = channel;
  }

  @Override
  public void completed(Integer result, ByteBuffer attachment) {
    attachment.flip();
    byte[] body = new byte[attachment.remaining()];
    attachment.get(body);
    try {
      System.out.println("Server receives message: ");
      System.out.println(new String(body, CharsetUtil.UTF_8));
      doWrite();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void doWrite() {
    ByteBuffer buffer = ByteBuffer.wrap(("Hello, I'm server. It's: " + new Date()).getBytes());
    channel.write(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
      @Override
      public void completed(Integer result, ByteBuffer attachment) {
        if (attachment.hasRemaining()) {
          channel.write(attachment, attachment, this);
        }
      }

      @Override
      public void failed(Throwable exc, ByteBuffer attachment) {
        try {
          channel.close();
        } catch (IOException e) {
          // ignore
        }
      }
    });
  }

  @Override
  public void failed(Throwable exc, ByteBuffer attachment) {
    try {
      channel.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
